package com.hll.shiro;

import com.hll.pojo.Users;
import com.hll.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 自定义Realm
 */
public class UserRealm extends AuthorizingRealm {

    //执行授权逻辑
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //给资源进行授权，使用AuthorizationInfo接口的实现类
        System.out.println("授权授权逻辑");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        //到数据库查询当前登录用户授权字符串
        //首先获取当前登录id
        Subject subject = SecurityUtils.getSubject();
        Users users = (Users)subject.getPrincipal();
        Users dbUser = userService.findById(users.getUid());
        //拿到授权字符串
        info.addStringPermission(dbUser.getPerms());
        return info;
    }

    //注入业务
    @Autowired
    private UserService userService;

    //执行认证逻辑
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
        System.out.println("执行认证逻辑");
        //编写shiro判断逻辑，判断用户名和密码
            //1.判断用户名和密码
        UsernamePasswordToken token=(UsernamePasswordToken)auth;
        String principal = (String) auth.getPrincipal();
        Users users=userService.findByName(token.getUsername());
        if(users==null){
            //判断用户名是否一致，不存在则用户不存在
            return  null;//shiro底层会抛出 UnKnowAccountException
        }
        //2.判断密码（用用户名找出用户密码）
        return new SimpleAuthenticationInfo(users,users.getPassword(),"");
    }
}
